import axios from 'axios';
import { ElMessage } from "element-plus";
import { useUserStore } from '../stores/user.js';
import router  from '../router'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        const userStore = useUserStore();
        let token = userStore.token
        if (token) {
            config.headers['Authorization-diy-report'] = "Bearer " + token;
        }
        if (config.method.toUpperCase() === 'POST') {
            config.headers['Content-Type'] = 'application/json;charset=utf-8'
        }
        if (config.pageInfo) {
            config.headers['X-Page-Index'] = config.pageInfo.pageNo
              ? config.pageInfo.pageNo
              : 1
            config.headers['X-Page-Size'] = config.pageInfo.pageSize
              ? config.pageInfo.pageSize
              : 20
            if (
              Array.isArray(config.pageInfo.orders) &&
              config.pageInfo.orders.length > 0
            ) {
              config.headers['X-Page-Sort'] = config.pageInfo.orders
            }
          }
        return config;
    },
    error => {
        // 处理请求错误
        ElMessage.error("系统无法处理您的访问请求，请检查数据并重试!")
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 处理响应数据
        const res = response.data;
        if (res.code === 0) {
            return res.data;
        } else if (res.code == 400 || res.code == 403) {
            ElMessage({
                message: res.msg,
                type: 'warning',
            })
        } else if (res.code == 401) {
            ElMessage({
                message: res.msg,
                type: 'warning',
            })
            localStorage.removeItem('token')
            const userStore = useUserStore();
            userStore.setToken(undefined)
            router.push("/login")
        } else if (res.code == 500) {
            ElMessage({
                message: res.msg,
                type: 'error',
            })
        }
        return Promise.reject();
    },
    error => {
        // 处理响应错误
        ElMessage.error("系统无法处理您的访问请求，请检查数据并重试!")
        return Promise.reject(error);
    }
);


export default service;

export function downloadFile(url, params = {}, filename = '', method = 'GET') {
  return service({
    url,
    method,
    params: method.toUpperCase() === 'GET' ? params : null,
    data: method.toUpperCase() === 'POST' ? params : null,
    responseType: 'blob', // 关键：指定响应类型为二进制流
  })
    .then((response) => {
      // 从响应头或自定义获取文件名
      const actualFilename = filename || 
        getFilenameFromHeaders(response.headers) || 
        `download_${new Date().getTime()}`;

      // 创建Blob对象并下载
      const blob = new Blob([response]);
      downloadBlob(blob, actualFilename);
    })
    .catch((error) => {
      // 处理Blob返回的错误信息（如JSON错误）
      if (error.response?.data?.type?.includes('application/json')) {
        const reader = new FileReader();
        reader.onload = () => {
          try {
            const errorData = JSON.parse(reader.result);
            ElMessage.error(errorData.msg || '下载失败');
          } catch (e) {
            ElMessage.error('文件下载失败');
          }
        };
        reader.readAsText(error.response.data);
      } else {
        ElMessage.error('文件下载失败');
      }
      return Promise.reject(error);
    });
}